<template>
  <div class="app-container">
    <h2 style="text-align: center;">发布新课程</h2>
    <el-steps :active="2" process-status="wait" align-center style="margin-bottom: 40px;">
      <el-step title="填写课程基本信息"/>
      <el-step title="创建课程大纲"/>
      <el-step title="提交审核"/>
    </el-steps>
    <el-form label-width="120px">
      <el-button type="text" @click="openChapterDialog">添加章节</el-button>
      
      <!-- 添加和修改章节表单 -->
      <el-dialog :visible.sync="dialogChapterFormVisible" title="添加章节">
          <el-form :model="chapter" label-width="120px">
              <el-form-item label="章节标题">
                  <el-input v-model="chapter.title"/>
              </el-form-item>
              <el-form-item label="章节排序">
                  <el-input-number v-model="chapter.sort" :min="0" controls-position="right"/>
              </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
              <el-button @click="dialogChapterFormVisible = false">取 消</el-button>
              <el-button type="primary" @click="updatedOrSave">确 定</el-button>
          </div>
      </el-dialog>

      <!-- 添加和修改课时表单 -->
      <el-dialog :visible.sync="dialogVideoFormVisible" title="添加课时">
        <el-form :model="video" label-width="120px">
          <el-form-item label="课时标题">
            <el-input v-model="video.title"/>
          </el-form-item>
          <el-form-item label="课时排序">
            <el-input-number v-model="video.sort" :min="0" controls-position="right"/>
          </el-form-item>
          <el-form-item label="是否免费">
            <el-radio-group v-model="video.free">
              <el-radio :label="true">免费</el-radio>
              <el-radio :label="false">默认</el-radio>
            </el-radio-group>
          </el-form-item>

          <!-- 上传视频(这里设置了最大上传数属性limit为1,防止多个文件同时上传出现问题) -->
          <el-form-item label="上传视频">
            <el-upload
                  :on-success="handleVodUploadSuccess"
                  :on-remove="handleVodRemove"
                  :before-remove="beforeVodRemove"
                  :on-exceed="handleUploadExceed"
                  :file-list="fileList"
                  :action="BASE_API+'/eduvod/video/uploadAliyunVideo'"
                  :limit="1"
                  class="upload-demo">
              <el-button size="small" type="primary">上传视频</el-button>
              <el-tooltip placement="right-end">
                  <div slot="content">最大支持1G，<br>
                      支持3GP、ASF、AVI、DAT、DV、FLV、F4V、<br>
                      GIF、M2T、M4V、MJ2、MJPEG、MKV、MOV、MP4、<br>
                      MPE、MPG、MPEG、MTS、OGG、QT、RM、RMVB、<br>
                      SWF、TS、VOB、WMV、WEBM 等视频格式上传</div>
                  <i class="el-icon-question"/>
              </el-tooltip>
            </el-upload>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogVideoFormVisible = false">取 消</el-button>
          <el-button :disabled="saveVideoBtnDisabled" type="primary" @click="saveOrUpdateVideo">确 定</el-button>
        </div>
      </el-dialog>
      
      <!-- 章节 -->
      <ul class="chanpterList">
          <li
              v-for="item in ChapterVideoList"
              :key="item.id">
              <p>
                  {{ item.title }}
                  <span class="acts">
                      <el-button type="text" @click="openVideo(item.id)">添加课时</el-button>
                      <el-button type="text" @click="openChapterEditDialog(item.id)">编辑</el-button>
                      <el-button type="text" @click="deleteChapter(item.id)">删除</el-button>
                  </span>
              </p>

              <!-- 小节 -->
              <ul class="chanpterList videoList">
                  <li
                      v-for="video in item.children"
                      :key="video.id">
                      <p>{{ video.title }}
                          <span class="acts">
                              <el-button type="text">编辑</el-button>
                              <el-button type="text" @click="deleteVideo(video.id)">删除</el-button>
                          </span>
                      </p>
                  </li>
              </ul>
          </li>
      </ul>

      <el-form-item>
        <el-button @click="previous">上一步</el-button>
        <el-button :disabled="saveBtnDisabled" type="primary" @click="next">下一步</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import chapterApi from "@/api/edu/chapter"
import videoApi from '@/api/edu/video'

export default {
  data() {
    return {
      chapter: {
      title: '',
      sort: 0,
      courseId : 0, // 该课程的课程id值
      },
      video: {
        title: '',
        sort: 0,
        free: 0,
        videoSourceId: '',
        videoOriginalName:'' // 视频源文件名称
      },
      saveBtnDisabled: false, // 保存按钮是否禁用
      ChapterVideoList: [], // 保存该课程大纲的所有信息
      dialogChapterFormVisible : false, // 章节表单弹框是否显示
      dialogVideoFormVisible: false, // 小节弹框是否显示
      saveVideoBtnDisabled: false, // 小节弹框确定按钮是否禁用
      BASE_API:process.env.BASE_API,
      fileList: [],//上传文件列表
    }
  },

  created() {
    // 根据路由来获取课程id值
    if(this.$route.params && this.$route.params.id){
      this.chapter.courseId = this.$route.params.id
    }
    this.getChapterVideo()
  },

  methods: {
    previous() {
      console.log('previous')
      this.$router.push({ path: '/course/info/' + this.chapter.courseId })
    },

    next() {
      console.log('next')
      this.$router.push({ path: '/course/publish/' + this.chapter.courseId })
    },

    // 获取所有课程大纲信息
    getChapterVideo(){
      chapterApi.getChapterVideoByCourseId(this.chapter.courseId)
      .then(response => {
        this.ChapterVideoList = response.data.allChapterVideo
      }).catch(error => {
        this.$message({
          type:'error',
          message:error.message
        })
      })
    },

    // 弹出表单
    openChapterDialog(){
      // 清空表单数据
      this.chapter.title = ''
      this.chapter.sort = 0

      this.dialogChapterFormVisible = true
    },

    // 添加章节信息
    addChapter(){
      chapterApi.addChapter(this.chapter)
      .then( response => {
        this.$message({
          type: 'success',
          message: '添加章节成功!'
        })
        this.dialogChapterFormVisible = false
        this.getChapterVideo()
      }).catch( error => {
        this.$message({
          type: 'error',
          message: error.message
        })
      })
    },

    // 更新章节信息
    updatedChaper(){
      chapterApi.updatedChapterInfo(this.chapter)
      .then(response => {
        chapterApi.updatedChapterInfo(this.chapter)
        .then(response => {
          this.dialogChapterFormVisible = false
          this.$message({
            type: 'success',
            message: '更新章节信息成功!'
          })
          // 数据刷新
          this.getChapterVideo()
        })
      })
    },

    // 对话框的确定按钮点击事件
    updatedOrSave(){
      if(!this.chapter.id){
        this.addChapter()
      }else{
        this.updatedChaper()
      }
    },

    // 打开章节编辑对话框
    openChapterEditDialog(chapterId){
      this.openChapterDialog()
      // 填充属性 
       chapterApi.getChapterInfoById(chapterId)
       .then( response => {
         this.chapter = response.data.chapter
       })
    },

    // 删除章节
    deleteChapter(chapterId){
      // 弹出确认框
      this.$confirm('此操作将删除该章节, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          chapterApi.deletdChapterById(chapterId)
          .then(response => {
            this.$message({
            type: 'success',
            message: '删除成功!'
          })
          // 刷新章节
          this.getChapterVideo()
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
    },

    // 打开添加小节窗口
    openVideo(chapterId){
      // 清空数据
      this.video = {}
      this.fileList = []
      // 显示弹框
      this.dialogVideoFormVisible = true
      // 设置属性
      this.video.chapterId = chapterId
    },

    // 添加小节
    addVideo(){
      this.video.courseId = this.chapter.courseId
      videoApi.addVideo(this.video)
      .then(response => {
        this.$message({
            type: 'success',
            message: '添加章节成功!'
          })
        // 刷新数据
        this.getChapterVideo()
        // 关闭弹窗
        this.dialogVideoFormVisible = false
      })
    },

    saveOrUpdateVideo(){
      this.addVideo()
    },

    // 删除章节
    deleteVideo(videoId){
      this.$confirm('此操作将删除该小节, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          // 删除小节
          videoApi.deleteVideoById(videoId)
          .then(response => {
            this.$message({
              type:'success',
              message:'删除小节成功!'
            })
            // 刷新章节
            this.getChapterVideo()
          }).catch(error => {
            this.$message({
            type: 'error',
            message: '删除小节失败!'
            })
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
    },

    // 上传视频成功回调
    handleVodUploadSuccess(response, file, fileList) {
      this.video.videoSourceId = response.data.videoId
      this.video.videoOriginalName = file.name
      console.log(this.video.videoSourceId)
      console.log(this.video.videoOriginalName)
    },

    // 视图上传多于一个视频
    handleUploadExceed(files, fileList) {
      this.$message.warning('想要重新上传视频，请先删除已上传的视频')
    },

    // 删除视频所调用的方法
    handleVodRemove(){
      videoApi.deleteAliyunVideoByVideoId(this.video.videoSourceId)
      .then( response => {
        this.$message({
          type: 'success',
          message: '删除视频成功!'
        })
        // 清空文件列表
        this.fileList = []
      })
    },

    // 点击x所调用的方法
    beforeVodRemove(file){
      return this.$confirm(`确定移除 ${ file.name }？`)
    }
  }
}
</script>
<style scoped>
.chanpterList{
    position: relative;
    list-style: none;
    margin: 0;
    padding: 0;
}
.chanpterList li{
  position: relative;
}
.chanpterList p{
  /* float: left; */
  font-size: 20px;
  margin: 10px 0;
  padding: 10px;
  height: 70px;
  line-height: 50px;
  width: 100%;
  border: 1px solid #DDD;
}
.chanpterList .acts {
    float: right;
    font-size: 14px;
}

.videoList{
  padding-left: 50px;
}
.videoList p{
  /* float: left; */
  font-size: 14px;
  margin: 10px 0;
  padding: 10px;
  height: 50px;
  line-height: 30px;
  width: 100%;
  border: 1px dotted #DDD;
}

</style>